﻿using System;
using System.IO;
using System.Text;

namespace Vibstudio.X4NET.Text.Encoding
{
    public static class EncodableExtensions
    {
        public static byte[] ToBytes(this string str, System.Text.Encoding encoding)
        {
            return encoding.GetBytes(str);
        }

        public static byte[] ToBytes(this string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

        public static byte[] ToBytes(this StringBuilder builder, System.Text.Encoding encoding)
        {
            return builder.ToString().ToBytes(encoding);
        }

        public static byte[] ToBytes(this StringBuilder builder)
        {
            return builder.ToString().ToBytes();
        }

        public static byte[] ToBytes(this Stream stream)
        {
            int length = Convert.ToInt32(stream.Length);
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, length);
            return bytes;
        }

        public static string ToText(this Stream stream)
        {
            return stream.ToBytes().ToText();
        }

        public static string ToText(this Stream stream, System.Text.Encoding encoding)
        {
            return stream.ToBytes().ToText(encoding);
        }

        public static string ToText(this byte[] bytes)
        {
            System.Text.Encoding defaultEncoding = System.Text.Encoding.UTF8;

            try
            {
                ICharsetDetector detector = new CharsetDetector();
                detector.Feed(bytes);
                detector.DataEnd();
                string charset = detector.Charset;

                return string.IsNullOrEmpty(charset)
                           ? defaultEncoding.GetString(bytes)
                           : System.Text.Encoding.GetEncoding(charset).GetString(bytes);
            }
            catch
            {
                return defaultEncoding.GetString(bytes);
            }
        }

        public static string ToText(this byte[] bytes, System.Text.Encoding encoding)
        {
            return encoding.GetString(bytes);
        }
    }
}
